<!-- src/views/layout/index.vue -->
<script setup>
import { ref, onMounted } from 'vue';
import router from '@/router';
import loginApi from '@/api/login_api.js';
import loginApi1 from '@/api/member_api.js';
import { ElMessageBox, ElMessage } from 'element-plus';

import {
  User, UserFilled, List,
  Document, PieChart, ShoppingCart,
  Box, Star, Expand, Fold, SwitchButton, Stamp
} from '@element-plus/icons-vue';

const activeIndex = ref('1');

// 当前登录用户
const loginAdmin = ref({
  user_id: '',
  username: '',
  real_name: '',
});

async function getUserName() {
  try {
    const res = await loginApi.loginInfo();
    const user = res?.data ?? res; // 兼容两种返回结构
    if (!user || !user.user_id) {
      ElMessage.error('无法获取用户信息');
      return;
    }
    loginAdmin.value = user;
    localStorage.setItem('user_id', String(user.user_id));
  } catch (e) {
    ElMessage.error('获取用户信息失败');
    console.error(e);
  }
}

onMounted(async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    router.push('/login');
    return;
  }
  await getUserName();
});

const isCollapse = ref(false);

const handleSelect = (key) => {
  console.log('顶部菜单选择:', key);
  if (key === 'logout') {
    logout();
  } else if (key === '1-1') {
    EditMessage();
    ElMessage.info('点击了"修改信息"');
  } else if (key === '1-2') {
    NewCode();
    ElMessage.info('点击了"重置密码"');
  }
};

const menuData = ref([
  {
    name: '用户管理',
    icon: User,
    children: [
      { name: '用户列表', icon: UserFilled, path: '/user/buyer' },
    ],
  },
  {
    name: '水果管理',
    icon: Box,
    children: [
      { name: '水果列表', icon: List, path: '/fruit/list' },
      { name: '收获记录', icon: Document, path: '/fruit/harvest' },
    ],
  },
  {
    name: '库存管理',
    icon: Box,
    children: [
      { name: '库存列表', icon: List, path: '/inventory/list' },
      { name: '库存预警', icon: PieChart, path: '/inventory/warning' },
    ],
  },
  {
    name: '订单管理',
    icon: ShoppingCart,
    children: [
      { name: '订单列表', icon: List, path: '/order/list' },
      { name: '订单详情', icon: Document, path: '/order/detail' },
    ],
  },
  {
    name: '爱心捐赠',
    icon: Star,
    children: [
      { name: '捐赠记录', icon: List, path: '/donation/list' },
      { name: '爱心总览', icon: PieChart, path: '/donation/total' },
    ],
  },
]);

function handleMenu(key) {
  if (key && typeof key === 'string') {
    router.push(key);
  }
}

function logout() {
  localStorage.removeItem('token');
  router.push('/login');
}

// 修改信息（用户名）
async function EditMessage() {
  const userId = loginAdmin.value.user_id || localStorage.getItem('user_id');
  if (!userId) {
    ElMessage.error('无法获取当前用户的 ID');
    return;
  }

  ElMessageBox.prompt('请输入新的用户名', '修改信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: loginAdmin.value.username,
    inputPattern: /^[a-zA-Z0-9_]{3,20}$/,
    inputErrorMessage: '用户名必须是3-20个字母、数字或下划线',
  })
      .then(async ({ value }) => {
        try {
          const resp = await loginApi1.edit({ user_id: userId, username: value });
          // 兼容两种结构
          const ok = resp?.code ? resp.code === 200 : true;
          if (ok) {
            ElMessage.success('用户名更新成功');
            // 重新拉取后端用户信息（更稳）
            await getUserName();
            // 可选：若后端签发新 token，你需要在此替换新的 token
            // localStorage.setItem('token', resp.data?.token)
            // 可选：强制重登，确保旧用户名/旧token不会带来错觉
            // localStorage.removeItem('token');
            // router.push('/login');
          } else {
            ElMessage.error(resp?.message || '用户名更新失败');
          }
        } catch (error) {
          console.error('更新用户名失败', error);
          ElMessage.error('请求失败，请稍后再试');
        }
      })
      .catch(() => {
        ElMessage.info('取消修改');
      });
}

// 重置密码
async function NewCode() {
  const userId = loginAdmin.value.user_id || localStorage.getItem('user_id');
  if (!userId) {
    ElMessage.error('无法获取当前用户的 ID');
    return;
  }

  ElMessageBox.prompt('请输入当前密码', '重置密码', {
    confirmButtonText: '下一步',
    cancelButtonText: '取消',
    inputType: 'password',
  })
      .then(async ({ value: currentPassword }) => {
        // TODO：可调用后端校验当前密码的接口
        ElMessageBox.prompt('请输入新密码', '重置密码', {
          confirmButtonText: '确认重置',
          cancelButtonText: '取消',
          inputType: 'password',
        })
            .then(async ({ value: newPassword }) => {
              try {
                const resp = await loginApi1.edit({ user_id: userId, password: newPassword });
                const ok = resp?.code ? resp.code === 200 : true;
                if (ok) {
                  ElMessage.success('密码重置成功，请重新登录');
                  // 密码变更后旧 token 应失效，强制重登
                  localStorage.removeItem('token');
                  router.push('/login');
                } else {
                  ElMessage.error(resp?.message || '密码重置失败');
                }
              } catch (error) {
                console.error('重置密码失败', error);
                ElMessage.error('请求失败，请稍后再试');
              }
            })
            .catch(() => {
              ElMessage.info('取消重置');
            });
      })
      .catch(() => {
        ElMessage.info('取消修改');
      });
}
</script>

<template>
  <div class="common-layout">
    <el-container style="min-height: 100vh;">
      <el-header class="header-container">
        <el-menu
            :default-active="activeIndex"
            mode="horizontal"
            background-color="#f0f9f0"
            text-color="#2e7d32"
            active-text-color="#1b5e20"
            @select="handleSelect"
        >
          <el-menu-item index="0" class="logo-item">
            <img style="height: 60px; vertical-align: middle;" src="@/assets/logo.png" alt="农村爱心水果">
            <span style="margin-left: 15px; font-size: 20px; color: #2e7d32;">农村爱心水果管理系统</span>
          </el-menu-item>

          <div style="flex: 1;"></div>

          <el-sub-menu index="1">
            <template #title>
              <el-icon><Stamp /></el-icon>
              <span style="margin-left: 5px;">{{ loginAdmin.username }}</span>
            </template>
            <el-menu-item index="1-1">修改信息</el-menu-item>
            <el-menu-item index="1-2">重置密码</el-menu-item>
            <el-menu-item index="logout">
              <el-icon><SwitchButton /></el-icon>
              <span style="margin-left: 5px;">退出</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>

      <el-container>
        <el-aside :width="isCollapse ? '60px' : '200px'" class="aside-container">
          <div class="collapse-btn">
            <el-icon @click="isCollapse = !isCollapse">
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
          </div>

          <el-menu
              mode="vertical"
              background-color="#2e7d32"
              text-color="#e8f5e9"
              active-text-color="#c8e6c9"
              :collapse="isCollapse"
              @select="handleMenu"
              class="side-menu"
          >
            <el-sub-menu
                v-for="(menu, index) in menuData"
                :key="index"
                :index="index.toString()"
            >
              <template #title>
                <el-icon><component :is="menu.icon" /></el-icon>
                <span v-if="!isCollapse">{{ menu.name }}</span>
              </template>

              <el-menu-item
                  v-for="(child, ind) in menu.children"
                  :key="ind"
                  :index="child.path"
              >
                <el-icon><component :is="child.icon" /></el-icon>
                <span v-if="!isCollapse">{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <el-main class="main-container">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.header-container {
  height: 80px !important;
  padding: 0 20px;
  border-bottom: 1px solid #c8e6c9;
}
.logo-item { padding-left: 20px !important; }
.aside-container {
  background-color: #2e7d32;
  box-shadow: 2px 0 5px rgba(46, 125, 50, 0.2);
}
.collapse-btn {
  height: 60px;
  display: flex; justify-content: center; align-items: center;
  color: #e8f5e9; background-color: #1b5e20; cursor: pointer;
}
.side-menu { border-right: none !important; }
.main-container { background-color: #f9fef9; padding: 20px; min-height: calc(100vh - 80px); }
::v-deep(.el-menu-item.is-active),
::v-deep(.el-sub-menu__title.is-active) { background-color: #1b5e20 !important; }
::v-deep(.el-icon) { color: inherit; }
</style>
